class_name Player
extends CharacterBody2D

signal energy_change

@onready var point_light_2d: PointLight2D = $PointLight2D
@onready var game_over: Control = $UILayer/GameOver

var light_state: bool = true
var max_energy: float = 600.0
var energy: float = 600.0:
	set(v):
		if v > 600.0:
			v = 600.0
		energy = v
		if energy < 0:
			light_state = false
			point_light_2d.energy = 0
		energy_change.emit()
var energy_reduction: float = 10.0
var energy_increase: float = 8.0
var in_safe: bool = false
var need_jiaobu: bool = true

func _ready() -> void:
	point_light_2d.energy = 0
	light_state = false

func _unhandled_input(event: InputEvent) -> void:
	if event.is_action_pressed("close_or_turn_light"):
		if light_state:
			point_light_2d.energy = 0
			light_state = false
		elif energy > 0:
			energy -= 10
			point_light_2d.energy = 1
			light_state = true

func _physics_process(delta: float) -> void:
	
	if not GameManager.player_should:
		return
	
	var dir = Input.get_vector("left", "right", "up", "down")
	velocity = dir * 50
	move_and_slide()
	
	if not dir.is_zero_approx():
		if need_jiaobu:
			need_jiaobu = false
			SoundManager.play_sfx("JiaoBu", randf_range(0.8, 1.2))
			var timer := Timer.new()
			timer.timeout.connect(func():
				need_jiaobu = true
				timer.queue_free()
				)
			self.add_child(timer)
			timer.start(0.4)
	else:
		need_jiaobu = true
	
	look_at(get_global_mouse_position())
	
	if light_state:
		energy -= energy_reduction * delta
	if in_safe:
		energy += energy_increase * delta

func die():
	print("玩家已死亡")
	game_over.show_game_over()

func _on_area_checker_area_entered(area: Area2D) -> void:
	in_safe = true

func _on_area_checker_area_exited(area: Area2D) -> void:
	in_safe = false
